import { login, getInfo } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // 登录接口 获取token
  async login({ commit }, userInfo) {
    const res = await login(userInfo)
    console.log(res)
    commit('SET_TOKEN', res.data.token)
    setToken(res.data.token)
  },

  // get user info
  async getInfo({ commit }) {
    const userinfo = await getInfo()
    console.log(userinfo.data)
    commit('SET_NAME', userinfo.data.name)
  },

  // user logout
  logout({ commit }) {
    removeToken()
    commit('SET_TOKEN', '')
    // commit('setUserInfo', '')
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
